﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Odyssey.Linq;
using SunTzu.Utility;
using Rea.Web.Models;
using Odyssey.Web.Models;
using SunTzu.Web;

namespace Odyssey.Web.Controllers
{
    public class AccountController : FrontBaseController
    {
        //
        // GET: /Account/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Register()
        {
            ViewData.Model = new tb_account();
            return View();
        }

        public ActionResult RegisterSuccess()
        {
            return View();
        }

        [HttpPost]
        public ActionResult DoRegister(tb_account account)
        {
            account.Password = Encryption.MD5Encrypt(account.Password);
            if (db.tb_accounts.Any(c => c.Email == account.Email))
            {
                SetMessage("对不起，" + account.Email + " 已注册！");
            }
            else if (account.SaveOrUpdate())
            {
                EmailSender.SendValidateEmail(account);
                return RedirectToAction("RegisterSuccess");
            }
            return View("Register", account);
        }

        public ActionResult Profile()
        {
            var account = LoginHelper.CurrentUser;
            ViewData.Model = account;
            return View();
        }

        [HttpPost]
        public ActionResult SaveProfile()
        {
            var account = db.tb_accounts.Single(c => c.Id == LoginHelper.CurrentUserId);
            HTMLHelper.BindModel(account);
            account.SaveOrUpdate();
            LoginHelper.Refresh();
            return RedirectToAction("Profile");
        }

        public ActionResult Validate(string email, string vc)
        {
            var account = db.tb_accounts.FirstOrDefault(c => c.Email == email && c.Password == vc);
            if (account != null)
            {
                account.IsValidate = true;
                if (account.SaveOrUpdate())
                {
                    // 验证成功
                    LoginHelper.CurrentUser = account;
                    EmailSender.SendValidateSuccess(account);
                    return Redirect("/UserCenter");
                }
            }
            return Redirect("/");
        }
    }
}
